package com.csx.governance.traffic.condition;

import cn.hutool.core.util.ObjectUtil;
import com.csx.governance.traffic.condition.constant.CompareOperator;
import com.csx.governance.traffic.condition.constant.ExpressionComponentType;
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @author cuisongxu
 * @date 2023/2/25 14:12
 */
@Getter
@AllArgsConstructor
public abstract class ExpressionComponent implements Component {

    /**
     * 参数键
     */
    protected String paramKey;

    /**
     * 操作符
     */
    protected CompareOperator operator;

    /**
     * 参数值
     */
    protected String paramValue;


    @Override
    public String getStatement() {
        return paramKey + " " + operator.symbol() + " " + paramValue;
    }

    public static abstract class Builder implements Component.Builder {

        @Override
        public Component build(String type, String... params) throws IllegalArgumentException {
            if(ExpressionComponentType.EXP.typeName().equals(type) || params.length >= ExpressionComponentType.EXP.requiredParamsNumber()) {
                CompareOperator operator = CompareOperator.fromNameOrSymbol(params[1]);
                if(ObjectUtil.isEmpty(operator)) {
                    throw new IllegalArgumentException("Illegal CompareOperator");
                }
                return doBuild(params[0], operator, params[2]);
            }else {
                throw new IllegalArgumentException("Illegal Expression");
            }
        }

        /**
         * 构造表达式
         * @param paramKey 参数键
         * @param operator 操作符
         * @param paramValue 参数值
         * @return 表达式组件
         */
        protected abstract Component doBuild(String paramKey, CompareOperator operator, String paramValue);
    }
}
